'''
个人意外综合保险
'''
import sys

sys.path.append('../')
from common.config import *
from db.mysql import MysqlClient
from itertools import product
from common.helper import Helper
from urllib.parse import urlencode
import requests
import json


class Spider(object):
    def __init__(self):

        self.mysql = MysqlClient()
        self.name = "个人意外综合保险"

    # 生成产品数据
    def genProductInfo(self):

        plan = {

            "planA": {
                # 个人人身意外伤害保险
                "personalAccident": [{"productId": "2271135", "money": "50000"}],
                # 附加意外伤害骨折保险
                "addAccidentInjured": ["", {"productId": "2271644", "money": "5000"},
                                       {"productId": "2271645", "money": "10000"}],
                # 附加个人意外伤害医疗保险
                "addAccidentTreatment": ["", {"productId": "2271646", "money": "5000"},
                                         {"productId": "2271647", "money": "10000"}],
                # 附加个人意外伤害住院津贴保险
                "addAccidentHospital": ["", {"productId": "2271649", "money": "50"},
                                        {"productId": "2271650", "money": "100"},
                                        {"productId": "2271651", "money": "200"}],
                # 附加意外伤害一级伤残补助金保险
                "addAccidentSerious": ["", {"productId": "2271652", "money": "50000"}],
                # 附加交通事故意外伤害加倍给付保险
                "addAccidentTraffic": ["", {"productId": "2271664", "money": "100000"}],
                # 职业代码
                "occupational": []

            },
            "planB": {
                # 个人人身意外伤害保险
                "personalAccident": [{"productId": "2271136", "money": "100000"}],
                # 附加意外伤害骨折保险
                "addAccidentInjured": ["", {"productId": "2271644", "money": "5000"},
                                       {"productId": "2271645", "money": "10000"}],
                # 附加个人意外伤害医疗保险
                "addAccidentTreatment": ["", {"productId": "2271646", "money": "5000"},
                                         {"productId": "2271647", "money": "10000"},
                                         {"productId": "2271648", "money": "50000"}],
                # 附加个人意外伤害住院津贴保险
                "addAccidentHospital": ["", {"productId": "2271649", "money": "50"},
                                        {"productId": "2271650", "money": "100"},
                                        {"productId": "2271651", "money": "200"}],
                # 附加意外伤害一级伤残补助金保险
                "addAccidentSerious": ["", {"productId": "2271653", "money": "100000"}],
                # 附加交通事故意外伤害加倍给付保险
                "addAccidentTraffic": ["", {"productId": "2271665", "money": "200000"}],
                # 职业代码
                "occupational": []

            },
            "planC": {
                # 个人人身意外伤害保险
                "personalAccident": [{"productId": "2271137", "money": "150000"}],
                # 附加意外伤害骨折保险
                "addAccidentInjured": ["", {"productId": "2271644", "money": "5000"},
                                       {"productId": "2271645", "money": "10000"}],
                # 附加个人意外伤害医疗保险
                "addAccidentTreatment": ["", {"productId": "2271646", "money": "5000"},
                                         {"productId": "2271647", "money": "10000"},
                                         {"productId": "2271648", "money": "50000"}],
                # 附加个人意外伤害住院津贴保险
                "addAccidentHospital": ["", {"productId": "2271649", "money": "50"},
                                        {"productId": "2271650", "money": "100"},
                                        {"productId": "2271651", "money": "200"}],
                # 附加意外伤害一级伤残补助金保险
                "addAccidentSerious": ["", {"productId": "2271654", "money": "150000"}],
                # 附加交通事故意外伤害加倍给付保险
                "addAccidentTraffic": ["", {"productId": "2271666", "money": "300000"}],
                # 职业代码
                "occupational": []

            },
            "planD": {
                # 个人人身意外伤害保险
                "personalAccident": [{"productId": "2271138", "money": "200000"}],
                # 附加意外伤害骨折保险
                "addAccidentInjured": ["", {"productId": "2271644", "money": "5000"},
                                       {"productId": "2271645", "money": "10000"}],
                # 附加个人意外伤害医疗保险
                "addAccidentTreatment": ["", {"productId": "2271646", "money": "5000"},
                                         {"productId": "2271647", "money": "10000"},
                                         {"productId": "2271648", "money": "50000"}],
                # 附加个人意外伤害住院津贴保险
                "addAccidentHospital": ["", {"productId": "2271649", "money": "50"},
                                        {"productId": "2271650", "money": "100"},
                                        {"productId": "2271651", "money": "200"}],
                # 附加意外伤害一级伤残补助金保险
                "addAccidentSerious": ["", {"productId": "2271655", "money": "200000"}],
                # 附加交通事故意外伤害加倍给付保险
                "addAccidentTraffic": ["", {"productId": "2271667", "money": "400000"}],
                # 职业代码
                "occupational": []

            },
            "planE": {
                # 个人人身意外伤害保险
                "personalAccident": [{"productId": "2271139", "money": "300000"}],
                # 附加意外伤害骨折保险
                "addAccidentInjured": ["", {"productId": "2271644", "money": "5000"},
                                       {"productId": "2271645", "money": "10000"}],
                # 附加个人意外伤害医疗保险
                "addAccidentTreatment": ["", {"productId": "2271646", "money": "5000"},
                                         {"productId": "2271647", "money": "10000"},
                                         {"productId": "2271648", "money": "50000"}],
                # 附加个人意外伤害住院津贴保险
                "addAccidentHospital": ["", {"productId": "2271649", "money": "50"},
                                        {"productId": "2271650", "money": "100"},
                                        {"productId": "2271651", "money": "200"}],
                # 附加意外伤害一级伤残补助金保险
                "addAccidentSerious": ["", {"productId": "2271656", "money": "300000"}],
                # 附加交通事故意外伤害加倍给付保险
                "addAccidentTraffic": ["", {"productId": "2271668", "money": "600000"}],
                # 职业代码
                "occupational": []

            },
            "planF": {
                # 个人人身意外伤害保险
                "personalAccident": [{"productId": "2271140", "money": "400000"}],
                # 附加意外伤害骨折保险
                "addAccidentInjured": ["", {"productId": "2271644", "money": "5000"},
                                       {"productId": "2271645", "money": "10000"}],
                # 附加个人意外伤害医疗保险
                "addAccidentTreatment": ["", {"productId": "2271646", "money": "5000"},
                                         {"productId": "2271647", "money": "10000"},
                                         {"productId": "2271648", "money": "50000"}],
                # 附加个人意外伤害住院津贴保险
                "addAccidentHospital": ["", {"productId": "2271649", "money": "50"},
                                        {"productId": "2271650", "money": "100"},
                                        {"productId": "2271651", "money": "200"}],
                # 附加意外伤害一级伤残补助金保险
                "addAccidentSerious": ["", {"productId": "2271657", "money": "400000"}],
                # 附加交通事故意外伤害加倍给付保险
                "addAccidentTraffic": ["", {"productId": "2271669", "money": "800000"}],
                # 职业代码
                "occupational": []

            },
            "planG": {
                # 个人人身意外伤害保险
                "personalAccident": [{"productId": "2271140", "money": "400000"}],
                # 附加意外伤害骨折保险
                "addAccidentInjured": ["", {"productId": "2271644", "money": "5000"},
                                       {"productId": "2271645", "money": "10000"}],
                # 附加个人意外伤害医疗保险
                "addAccidentTreatment": ["", {"productId": "2271646", "money": "5000"},
                                         {"productId": "2271647", "money": "10000"},
                                         {"productId": "2271648", "money": "50000"}],
                # 附加个人意外伤害住院津贴保险
                "addAccidentHospital": ["", {"productId": "2271649", "money": "50"},
                                        {"productId": "2271650", "money": "100"},
                                        {"productId": "2271651", "money": "200"}],
                # 附加意外伤害一级伤残补助金保险
                "addAccidentSerious": ["", {"productId": "2271658", "money": "500000"}],
                # 附加交通事故意外伤害加倍给付保险
                "addAccidentTraffic": ["", {"productId": "2271670", "money": "1000000"}],
                # 职业代码
                "occupational": []

            },
        }

        for k in plan:

            for v in product(plan[k]["personalAccident"], plan[k]["addAccidentInjured"],
                             plan[k]["addAccidentTreatment"], plan[k]["addAccidentHospital"],
                             plan[k]["addAccidentSerious"],plan[k]["addAccidentTraffic"]):


                print( domain[self.name]["insert_sql"].format(

                    "'" + json.dumps(v[0]) + "'" if isinstance( v[0],dict) else 'NULL',
                    "'" + json.dumps(v[1]) + "'"if isinstance( v[1],dict) else 'NULL',
                    "'" + json.dumps(v[2]) + "'"if isinstance( v[2],dict) else 'NULL',
                    "'" + json.dumps(v[3]) + "'"if isinstance( v[3],dict) else 'NULL',
                    "'" + json.dumps(v[4]) + "'"if isinstance( v[4],dict) else 'NULL',
                    "'" + json.dumps(v[5])+ "'"if isinstance( v[5],dict) else 'NULL' ))

                #写入数据库
                self.mysql.cursor.execute( domain[self.name]["insert_sql"].format(

                    "'" + json.dumps(v[0]) + "'" if isinstance( v[0],dict) else 'NULL',
                    "'" + json.dumps(v[1]) + "'"if isinstance( v[1],dict) else 'NULL',
                    "'" + json.dumps(v[2]) + "'"if isinstance( v[2],dict) else 'NULL',
                    "'" + json.dumps(v[3]) + "'"if isinstance( v[3],dict) else 'NULL',
                    "'" + json.dumps(v[4]) + "'"if isinstance( v[4],dict) else 'NULL',
                    "'" + json.dumps(v[5])+ "'"if isinstance( v[5],dict) else 'NULL' ))
                self.mysql._conn.commit()
                print("%s产品信息写入数据库成功"%self.name)

    #执行爬虫
    def requestJson(self,dt=None):

        productId = ""
        rdt = {

            "personalAccident":dt["personalAccident"],
            "addAccidentInjured":dt["addAccidentInjured"],
            "addAccidentTreatment":dt["addAccidentTreatment"],
            "addAccidentHospital":dt["addAccidentHospital"],
            "addAccidentSerious":dt["addAccidentSerious"],
            "addAccidentTraffic":dt["addAccidentTraffic"]
        }

        for v in rdt.values():

            if v:

                productId += json.loads(v)["productId"] +","

            else:

                continue


        data = {

        "random": "2766",
        "uuid":"",
        "orderId":"",
        "plaintext":"",
        "sign":"",
        "B2EUser":"",
        "productCode": "GRYWX",
        "productSerialNo": "GRYWX_planA",
        "unitPremium": "1493",
        "respNumber": "0",
        "drivingCostomType": "0",
        "discountRate": "1",
        "bxtk_url": "https: // www.cpic.com.cn / upload / Attach / mrbj",
        "checkType": "3",
        "otherSource": "10000",
        "channelNo": "10000",
        "productIds": productId,
        "productCodes": "GRYWX_SH, GRYWX_GZ, GRYWX_YL, GRYWX_JT, GRYWX_SC, GRYWX_SG,",
        "resCodes": "$sessionMap.get('resCodes')",
        "card": "GRYWX_planA",
        "insured_occupationClass": "09, 0902, 0902003",
        "insu_first_occupationName": "一般职业",
        "insu_second_occupationName": "广告业",
        "insu_third_occupationName": "广告招牌绘制人员（地面工作）",
        "insu_first_occupation": "00",
        "insu_second_occupation":"",
        "insu_occupationClass":"",
        "occupationalType": "A0005",
        "GRYWX_GZ":"",
        "GRYWX_YL":"",
        "GRYWX_JT":"",
        "GRYWX_SC":"",
        "GRYWX_SG":"",
        "inceptionDate": "2020 - 01 - 02",
        "plannedEndDate": "2021 - 01 - 01",
        "commonuuid": "not finduuid",
        }

        r = requests.post( url = domain[self.name]["url"],headers=domain[self.name]["header"],data=urlencode(data).replace('+',''))

        if r.status_code == 200 and r.json()["result"] == 0:

            price = Helper.decimalParse( r.json()["price"])

            data = {

                "name":self.name,
                "id":dt["id"],
                "price":price
            }
            self.mysql.updatePrice( data )


        else:

            # 任务执行失败
            data = {
                "name": self.name,
                "id": dt["id"],
                "state": 3
            }
            self.mysql.updateTask(data)

    def main(self):

        while True:

            # 随机领取一条数据
            dt = self.mysql.randTask(self.name)

            if not dt:
                print("产品价格抓取完成~~~")

                return

                # 任务执行状态
            data = {
                "name": self.name,
                "id": dt["id"],
                "state": 1
            }
            self.mysql.updateTask(data)

            self.requestJson(dt)





if __name__ == '__main__':
    s = Spider()

    s.main()
